package org.feng.common.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;

/**
 * 表格工具类
 *
 * @author fengjinsong
 */
public class ExcelUtil {

    /**
     * 写出表格到接口
     *
     * @param records                 数据列表
     * @param sheetName               sheet名
     * @param recordClass             指定数据类型
     * @param fileName                文件名
     * @param excludeColumnFiledNames 排除的列名（类属性名）
     * @param response                servlet响应
     * @param <T>                     数据类型
     * @throws IOException 文件操作涉及io
     */
    public static <T> void writeToWeb(List<T> records, String sheetName, Class<T> recordClass, String fileName, Set<String> excludeColumnFiledNames, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileNameTmp = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("filename", URLEncoder.encode(fileName, StandardCharsets.UTF_8) + ".xlsx");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameTmp + ".xlsx");

        ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream(), recordClass);

        // 指定排除的列
        if (!CollectionUtils.isEmpty(excludeColumnFiledNames)) {
            writerBuilder.excludeColumnFieldNames(excludeColumnFiledNames);
        }
        writerBuilder.sheet(sheetName).doWrite(records);
    }
}
